// pages/category/category.js

import { Category } from '../category/category-model.js';
var category = new Category;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentMenuIndex: 0,
    loadedData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._loadDate();
  },

  _loadDate: function () {
    category.getCategoryType((categoryData) => {
      this.setData({
        categoryTypeArr: categoryData
      });

      //再获取到分类的id后，通过某个分类的id获取到该分类的商品信息列表
      category.getProductsByCategory(categoryData[0].id, (data) => {
        var dataObj = {
          products: data,
          topImgUrl: categoryData[0].img.url,
          title: categoryData[0].name
        };

        this.setData({
          categoryProducts: dataObj,
        })
      });

    });
  },

  changeCategory: function (event) {

    var id = category.getDataSet(event, 'id'),
      index = category.getDataSet(event, 'index');

    //如果某个分类下的商品信息不存在，则从服务器请求，如果已经存在，则直接绑定
    if ( !this.isLoadedData(index) ) {
      category.getProductsByCategory(id, (data) => {

        var dataObj = {
          title: this.data.categoryTypeArr[index].name,
          topImgUrl: this.data.categoryTypeArr[index].img.url,
          products: data,
        };

        this.setData({
          categoryProducts: dataObj,
          currentMenuIndex: index
        });

        this.data.loadedData[index] = dataObj;

      });
    }else{
      this.setData({
        categoryProducts: this.data.loadedData[index],
        currentMenuIndex: index
      });
    }
  },

  //判断某个分类下的商品是否加载过
  isLoadedData(index) {
    if (this.data.loadedData[index]) {
      return true;
    }
    return false;
  },

  // 商品详情参数传递
  onProductsItemTap: function (event) {
    var id = category.getDataSet(event, 'id');
    wx.navigateTo({
      url: '../product/product?id=' + id,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

})